package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.soa.SoaManager;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.User;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCM2levelbaseaccount;
import com.baosight.sczx.zm.cm.domain.ZMCMBasicset;
import com.baosight.sczx.zm.cm.domain.ZMCMDepot;
import com.baosight.sczx.zm.cm.domain.ZMCMExportApplication;
import com.baosight.sczx.zm.cm.domain.ZMCMExportMaterial;
import com.baosight.sczx.zm.cm.domain.ZMCMExportmaterialDetail;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;

/**出库管理
 * <p>Title: ServiceZMCME0.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 余虎
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午12:59:26  余虎  Create
 *</pre>
 */
public class ServiceZMCME0 extends ServiceEPBase {

	/**初始化数据
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-5下午01:00:12 余虎
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		 inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		 EiInfo outInfo = this.query(inInfo);	
		 String DepotLevel = "一级";
		 Map map = new HashMap();
		 map.put("fdDepotLevel", DepotLevel);
		 List<ZMCMDepot> list = dao.query("ZMCMDepot.query",map);
		 outInfo.set("fdDepotCode", list.get(0).getFdDepotCode().toString());
		 outInfo.set("fdDepotName", list.get(0).getFdDepotName().toString());
         String fdUse2LevelBase = "";
	     Map _map = new HashMap();
         List<ZMCMBasicset> _list = dao.query("ZMCMBasicset.query",_map);
         if(_list.size() > 0)
         {
	         if(_list.get(0).getFdUse2levelbase().toString().equals("0")||_list.get(0).getFdUse2levelbase().toString()=="0")
	         {
	        	 fdUse2LevelBase = "0";
	         }
         }
         else
         {
        	 fdUse2LevelBase = "1";
         }
        outInfo.set("use2Level", fdUse2LevelBase);
		outInfo.addBlock(User.getInstance().getConstructionStaff("cmes.cm.emp", "empCode", "empName", false));
		String fdNoteCode = queryfdCode();
		outInfo.set("fdNoteCode", fdNoteCode);
		outInfo.set("userId", UserSession.getUserId());//用户Id默认填入库确认人
		outInfo.set("userName", UserSession.getInSessionProperty("UserCname"));//用户Name默认填入库确认人
		
		return outInfo;
	}
	
	/**
	 * 查询最新编号
	 * <p>Function: queryfdCode</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午10:55:12 余虎
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryfdCode()
	{
		
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "CK" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMExportMaterial.queryLatestNoteCode", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		return defaultStr;
	}
	/**
	 * 构造编号
	 * <p>Function: convertStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午10:52:36 余虎
	 * </p>
	 *
	 */
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(16,19);//第二部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
	
	/**
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-5下午01:00:12 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo query(EiInfo inInfo) {
		EiInfo outInfo = super.query(inInfo, "ZMCMExportMaterial.query", new ZMCMExportMaterial());		
		return outInfo;
	}
	/**红冲
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-5下午01:00:12 余虎
	 * </p>
	 *
	*/
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{	
		boolean validateType = validateTypeManagement(inInfo);
		if(validateType)
		{
			return inInfo;
		}
		
        boolean validateValue = validate(inInfo, "ZMCMExportMaterial.validate", new HashMap<String, String>());
        
		if(validateValue) {
			return inInfo;
		}
		else 
		{
			int result_int = MaterialBase.isInAccountDate(inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdNoteDate"));
			if(result_int == -2 || result_int == 0)
			{
				inInfo.setStatus(-1);
				StringBuffer msg = new StringBuffer("选中记录的单据日期已经超出" + MaterialBase.getAccountDate(StaticTools.getDate())[2] + "月的记账范围，不能办理红冲！");
				inInfo.setMsg(msg.toString());
				return inInfo;
			}
			
			String zbStatus="部分";//修改申请主表领用状态
			String fdNoteCode = inInfo.getBlock("result").getCellStr(0, "fdNoteCode");//单据编号
			String fdExportType = inInfo.getBlock("result").getCellStr(0, "fdExportType");//出库类型
			String oldKeyId =  inInfo.getBlock("result").getCellStr(0, "fdKeyId");//主键
			String fdNoteDate = inInfo.getBlock("result").getCellStr(0, "fdNoteDate");//开单日期
			String fdDepotCode = inInfo.getBlock("result").getCellStr(0, "fdDepotCode");//库房编号
			String fdDepotName = inInfo.getBlock("result").getCellStr(0, "fdDepotName");//库房名称
			
			String KeyId = TablePk.getInstance().getNextValue("T_CM_EXPORTMATERIAL");//主表主键
			inInfo.getBlock("result").setCell(0, "fdKeyId",KeyId);//主键
			if(fdNoteCode.length() > 27)
			{
				inInfo.getBlock("result").setCell(0, "fdNoteCode", "HC_"+fdNoteCode.substring(0, 27));
			}
			else
			{
				inInfo.getBlock("result").setCell(0, "fdNoteCode", "HC_"+fdNoteCode);
			}
			inInfo.getBlock("result").setCell(0, "fdResourceNoteCode", fdNoteCode);
			inInfo.getBlock("result").setCell(0, "fdNoteDate", fdNoteDate);
			inInfo.getBlock("result").setCell(0, "fdDepotCode", fdDepotCode);
			inInfo.getBlock("result").setCell(0, "fdDepotName", fdDepotName);
			inInfo.getBlock("result").setCell(0, "fdExportType", "红冲");
			inInfo.getBlock("result").setCell(0, "fdYear", MaterialBase.getAccountDate(fdNoteDate)[0]);
			inInfo.getBlock("result").setCell(0, "fdMonth", MaterialBase.getAccountDate(fdNoteDate)[1]);
			EiInfo outInfo = super.insert(inInfo, "ZMCMExportMaterial.insert");//新增红冲出库单
			
			Double fdActualNumber = new Double(0);
			Double actualExportSum = new Double(0);//获取页面中实际操作的额度 
			Double fdSum = null;
			Map<String, String> _map = new HashMap();
			_map.put("fdExportmaterialId", oldKeyId);
			List<ZMCMExportmaterialDetail> list = dao.query("ZMCMExportmaterialDetail.query",_map);	
			if(list.size()>0)
			{
				for (int i = 0 ; i<list.size();i++)
				{
					fdActualNumber = -(list.get(i).getFdActualNumber());
					fdSum = -(list.get(i).getFdSum());
					actualExportSum = actualExportSum + fdSum;
					Double fdExportedNumber = new Double(0);

					if(inInfo.getBlock("result")==null)
					{
						inInfo.addBlock("result");
					}
					fdExportedNumber = Double.valueOf(list.get(i).getFdExportedNumber().toString());
					fdExportedNumber = fdExportedNumber + fdActualNumber;
					
					String CkeyId = TablePk.getInstance().getNextValue("T_CM_EXPORTMATERIAL_DETAIL");//从表主键
					//inInfo.getBlock("result").setCell(i, "applicationfdKeyId", list.get(i).getApplicationfdKeyId().toString());//领料从表主键

					inInfo.getBlock("result").setCell(i, "fdApplicationId", list.get(i).getFdApplicationId().toString());
					inInfo.getBlock("result").setCell(i, "fdApplyDepartmentId", list.get(i).getFdApplyDepartmentId().toString());
					inInfo.getBlock("result").setCell(i, "initKeyId", list.get(i).getFdApplicationDetailId().toString());
					inInfo.getBlock("result").setCell(i, "fdBusinessType", list.get(i).getFdBusinessType()==null ? "":list.get(i).getFdBusinessType().toString());
					inInfo.getBlock("result").setCell(i, "fdMaterialType", list.get(i).getFdMaterialType()==null ? "":list.get(i).getFdMaterialType().toString());
					inInfo.getBlock("result").setCell(i, "fdMaterialId", list.get(i).getFdMaterialId().toString());
					inInfo.getBlock("result").setCell(i, "fdMaterialCode", list.get(i).getFdMaterialCode().toString());
					inInfo.getBlock("result").setCell(i, "fdMaterialName", list.get(i).getFdMaterialName().toString());
					inInfo.getBlock("result").setCell(i, "fdSpecModel", list.get(i).getFdSpecModel()==null ? "":list.get(i).getFdSpecModel().toString());
					inInfo.getBlock("result").setCell(i, "fdNumber", list.get(i).getFdNumber()==null ? "":list.get(i).getFdNumber().toString());
					inInfo.getBlock("result").setCell(i, "fdQuality", list.get(i).getFdQuality()==null ? "":list.get(i).getFdQuality().toString());
					inInfo.getBlock("result").setCell(i, "fdMetric", list.get(i).getFdMetric()==null ? "" :list.get(i).getFdMetric().toString());
					inInfo.getBlock("result").setCell(i, "fdActualNumber", fdActualNumber);
					inInfo.getBlock("result").setCell(i, "fdSum", fdSum);
					inInfo.getBlock("result").setCell(i, "fdStatus", list.get(i).getFdStatus()==null ? "" :list.get(i).getFdStatus().toString());
					inInfo.getBlock("result").setCell(i, "fdPrice", list.get(i).getFdPrice()==null ? 0:list.get(i).getFdPrice().toString());
					inInfo.getBlock("result").setCell(i, "fdExportmaterialId", KeyId);//外键
					inInfo.getBlock("result").setCell(i, "fdKeyId", CkeyId);//主键					
					inInfo.getBlock("result").setCell(i, "fdExportedNumber", fdActualNumber);

					BigDecimal data1 = new BigDecimal(fdExportedNumber);
					BigDecimal data2 = new BigDecimal(0);

					if(data1.compareTo(data2) == 0)
					{   
						 inInfo.getBlock("result").setCell(i, "fdStatus", "");        		
					}
					 else
					{   
						 inInfo.getBlock("result").setCell(i, "fdStatus", "部分领用");
					}
					
					 if(!list.get(i).getFdBusinessType().toString().equals("一般"))
					 {
						 Map<String, String> _turnovermap = new HashMap<String, String>();
						 _turnovermap.put("fdKeyId", list.get(i).getFdTurnoverRecordlId().toString());
						 dao.delete("ZMCMTurnoverRecord.deleteFromHC",_turnovermap);
					 }
				}
				super.insert(inInfo, "ZMCMExportmaterialDetail.insert");//新增出库明细
				
				 
				inInfo.set(EiConstant.serviceName, "ZMCM80");	//修改领料申请--主表领料状态
				inInfo.set(EiConstant.methodName, "updateForStatus");
				inInfo.set("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdApplicationId"));
				inInfo.set("fdStatus", zbStatus);
				SoaManager.invoke(inInfo);
				
				inInfo.set(EiConstant.serviceName, "ZMCM81");	//修改领料申请--明细领料状态
				inInfo.set(EiConstant.methodName, "updateForStatus");
				for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
				{
					inInfo.getBlock("result").setCell(i, "fdKeyId", inInfo.getBlock("result").getCellStr(i, "fdApplicationDetailId"));
				}
				
				SoaManager.invoke(inInfo);
				super.update(inInfo, "ZMCMExportApplicationDetail.updateForExportedNumber");
				 	 
				outInfo.getBlock("result").setCell(0, "fdYear", list.get(0).getFdYear().toString());
				outInfo.getBlock("result").setCell(0, "fdMonth", list.get(0).getFdMonth().toString());
				outInfo.getBlock("result").setCell(0, "orgCode", list.get(0).getFdApplicationDepartment().toString());
				outInfo.getBlock("result").setCell(0, "fdExportRation", actualExportSum.toString());
				super.update(outInfo,"ZMCMMaterialRation.updateExportRation");  
				
				validateBaseNum(inInfo, oldKeyId, fdExportType);
				update_ZMCMMaterialBase(inInfo, fdExportType);
				 
				insert_2LEVELBASEACCOUNT(oldKeyId);
			} 

			return outInfo;
		}
	}

	

	/**
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-5下午01:00:12 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo update(EiInfo inInfo) {
		return super.update(inInfo);
	}
	/**
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-5下午01:00:12 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo delete(EiInfo inInfo) {
		return super.delete(inInfo);
	}

	 /** 获取领料申请单信息customview
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午05:16:05 余虎
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo queryForApplication(EiInfo inInfo) 
	{
		String typeCode = "";
		Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdExportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			List queryList = Utils.generateValidateData(_list);
			typeCode = "(c.fd_material_code like ''";
			for(int j=0; j<queryList.size(); j++)
			{
				typeCode += " OR c.fd_material_code like '" + queryList.get(j).toString() + "%'";
			}
			typeCode += ")";
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List queryList = dao.query(sqlmap, inMap);
			
			typeCode = "(c.fd_material_code like ''";
			for(int i=0; i<queryList.size(); i++)
			{
				Map _map = (Map)queryList.get(i);
				typeCode += " OR c.fd_material_code like '" + _map.get("fdTypeCode").toString() + "%'";
			}
			typeCode += ")";
		}

		if(inInfo.getBlock(EiConstant.queryBlock) == null)
		{
			inInfo.addBlock(EiConstant.queryBlock);
		}
		inInfo.getBlock(EiConstant.queryBlock).setCell(0, "fdMaterialCodeStr", typeCode);
		EiInfo outInfo = super.query(inInfo, "ZMCMExportApplication.queryInterface", new ZMCMExportApplication());
		return outInfo;
	}
	
	/**
	 * 红冲重复校验
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18下午04:37:28 余虎
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
        String fdNoteCode = inInfo.getBlock("result").getCellStr(0, "fdNoteCode");
        String fdExportType = inInfo.getBlock("result").getCellStr(0, "fdExportType");
        params.put("fdResourceNoteCode", fdNoteCode);
		params.put("fdExportType", fdExportType);

		List result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			ZMCMExportMaterial _temp = (ZMCMExportMaterial)result.get(0);
			StringBuffer msg = new StringBuffer("提交失败，");
			if(_temp.getFdNoteCode() != null && _temp.getFdNoteCode().equals(fdNoteCode)) {
				msg.append("");
			}
			if(_temp.getFdExportType() != null && _temp.getFdExportType().equals(fdExportType)) {
				msg.append("");
			}

			msg.append("该单据已进行红冲！");
			inInfo.setMsg(msg.toString());
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * <p>Function: validateTypeManagement</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:38:43 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean validateTypeManagement(EiInfo inInfo)
	{
		List link = new ArrayList();
		String oldKeyId =  inInfo.getBlock("result").getCellStr(0, "fdKeyId");//主键
           	
    	Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdExportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			link = Utils.generateValidateData(_list);
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List _list = dao.query(sqlmap, inMap);
    		
			for(int i = 0; i<_list.size(); i++)
			{
				Map _map = (Map)_list.get(i);
				link.add(_map.get("fdTypeCode").toString());
			}
		}
        
		Map<String, String> _map = new HashMap();
		_map.put("fdExportmaterialId", oldKeyId);
		List<ZMCMExportmaterialDetail> list = dao.query("ZMCMExportmaterialDetail.query",_map);	
		
		for(int j=0; j<list.size(); j++)
		{
			ZMCMExportmaterialDetail detail = list.get(j);
			String materialCode = detail.getFdMaterialCode();
			
			boolean flag = false;
			for(int k=0; k<link.size(); k++)
			{
				if(materialCode.startsWith(link.get(k).toString()))
				{
					flag = true;
				}
			}
			
			if(!flag)
			{
				inInfo.setStatus(-1);
				inInfo.setMsg("当前登录用户不具有该出库单中部分物资的分管权限，不允许红冲！");
				return true;
			}
		}
		
		return false;
	}
	
	private void validateBaseNum(EiInfo inInfo, String fdKeyId, String fdExportType)
	{	
		if(fdExportType.equals("一般出库"))
		{
			for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
			{
				String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
				String fdMaterialType = inInfo.getBlock("result").getCellStr(i, "fdMaterialType");
				String fdActualNumber = inInfo.getBlock("result").getCellStr(i, "fdActualNumber");
				
				Map inMap = new HashMap();
				inMap.put("fdMaterialId", fdMaterialId);
				List _list = dao.query("ZMCMMaterialBase.query", inMap);
	
				if(_list.size()>0)
				{
					ZMCMMaterialBase base = (ZMCMMaterialBase)_list.get(0);
					if(fdMaterialType.equals("有发票"))
					{
						inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", (0-Double.parseDouble(fdActualNumber)+base.getFdHasinvoiceNum()));
					}
					else
					{
						inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", (0-Double.parseDouble(fdActualNumber)+base.getFdNoinvoiceNum()));
					}
				}
			}
		}
	}
	
	/**
	 * 
	 * <p>Function: update_ZMCMMaterialBase</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:39:29 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private EiInfo update_ZMCMMaterialBase(EiInfo inInfo, String fdExportType)
	{
		EiInfo _info = new EiInfo();
		EiBlock _block = new EiBlock(EiConstant.resultBlock);
		_block.addBlockMeta((new ZMCMMaterialBase()).eiMetadata);
		_info.addBlock(new EiBlock(EiConstant.resultBlock));
		
		for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		{
			String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
			Map _map = new HashMap();
			_map.put("fdMaterialId", fdMaterialId);
			
			List _list = dao.query("ZMCMMaterialBase.query", _map);

			if(_list.size() > 0)
			{
				ZMCMMaterialBase mb = (ZMCMMaterialBase)_list.get(0);
				
				double cfdNum = mb.getFdNum();//库存数量
				double cfdPrice = mb.getFdPrice();//计划单价
				double cfdActualPrice = mb.getFdActualPrice();//实际单价
				double fdActualNum = 0-Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdActualNumber"));
				
				Map inMap = new HashMap();
				inMap.put("fdSum", BigDecimal.valueOf((cfdNum+fdActualNum)*cfdPrice));
				inMap.put("fdNum", (cfdNum+fdActualNum));
				inMap.put("fdActualSum", BigDecimal.valueOf((cfdNum+fdActualNum)*cfdActualPrice));
				inMap.put("fdLastExportDate", StaticTools.getDate());
				inMap.put("fdMaterialId", fdMaterialId);
				
				if(inInfo.getBlock("result").getCellStr(i, "fdHasinvoiceNum") == null 
						||inInfo.getBlock("result").getCellStr(i, "fdHasinvoiceNum") == ""
						||fdExportType.equals("超前出库"))
				{
					inMap.put("fdHasinvoiceNum", mb.getFdHasinvoiceNum());
				}
				else
				{
					inMap.put("fdHasinvoiceNum", inInfo.getBlock("result").getCell(i, "fdHasinvoiceNum"));
				}
				
				if(inInfo.getBlock("result").getCellStr(i, "fdNoinvoiceNum") == null 
						||inInfo.getBlock("result").getCellStr(i, "fdNoinvoiceNum") == ""
						||fdExportType.equals("超前出库"))
				{
					inMap.put("fdNoinvoiceNum", mb.getFdNoinvoiceNum());
				}
				else
				{
					inMap.put("fdNoinvoiceNum", inInfo.getBlock("result").getCell(i, "fdNoinvoiceNum"));
				}
				
				dao.update("ZMCMMaterialBase.updateAfterExport", inMap);
				
				if(fdExportType.equals("一般出库"))
				{
					if(inInfo.getBlock("result").getCellStr(i, "fdMaterialType").equals("无发票"))
					{
						if(fdActualNum-mb.getFdNoinvoiceUseNum()>0)
						{
							inMap.put("fdNoInvoiceUseNum", "0");
						}
						else
						{
							inMap.put("fdNoInvoiceUseNum", mb.getFdNoinvoiceUseNum()-fdActualNum);
						}
						dao.update("ZMCMMaterialBase.updateNoInvoiceUseNum", inMap);
					}
				}
			}
		 }
		
		 return new EiInfo();
	}
	
	/**
	 * 
	 * <p>Function: insert_2LEVELBASEACCOUNT</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:39:36 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void insert_2LEVELBASEACCOUNT(String oldKeyId)
	{
		Map inMap = new HashMap();
		inMap.put("fdExportNoteId", oldKeyId);
		
		List _list = dao.query("ZMCM2levelbaseaccount.query", inMap);
		
		for(int i=0; i<_list.size(); i++)
		{
			//生成二级库存红冲单据
			Map _map = new HashMap(); 
			ZMCM2levelbaseaccount lc = (ZMCM2levelbaseaccount)_list.get(i);
			
			String fdKeyId = TablePk.getInstance().getNextValue("T_CM_2LEVELBASEACCOUNT");
			
			_map.put("fdKeyId", fdKeyId);
			_map.put("fdDate", StaticTools.getDate());
			_map.put("fdType", "红冲");
			_map.put("fdDepotCode", lc.getFdDepotCode());
			_map.put("fdDepotName", lc.getFdDepotName());
			_map.put("fdMaterialId", lc.getFdMaterialId());
			_map.put("fdMaterialCode", lc.getFdMaterialCode());
			_map.put("fdMaterialInnerCode", lc.getFdMaterialInnerCode());
			_map.put("fdMaterialName", lc.getFdMaterialName());
			_map.put("fdMaterialType", lc.getFdMaterialType());
			_map.put("fdSpecModel", lc.getFdSpecModel());
			_map.put("fdNumber", lc.getFdNumber());
			_map.put("fdQuality", lc.getFdQuality());
			_map.put("fdMetric", lc.getFdMetric());
			_map.put("fdNum", 0-lc.getFdNum());
			_map.put("fdPlanPrice", lc.getFdPlanPrice());
			_map.put("fdPrice", lc.getFdPrice());
			_map.put("fdDepartment", lc.getFdDepartment());
			
			dao.insert("ZMCM2levelbaseaccount.insert", _map);
			
			//更新二级库存
			_map = new HashMap();
			_map.put("fdMaterialId", lc.getFdMaterialId());
			_map.put("fdDepotCode", lc.getFdDepotCode());
			
			List tmp = dao.query("ZMCM2levelmaterialbase.validateexist", _map);
			
			if(tmp.size() > 0)
			{
				Map tmp1 = (Map)tmp.get(0);
				double fdNum = Double.parseDouble(tmp1.get("fdNum").toString());
				//double fdPlanPrice = Double.parseDouble(tmp1.get("fdPlanPrice").toString());
				double fdPrice = Double.parseDouble(tmp1.get("fdPrice").toString());
				double actualNum = lc.getFdNum();
				double cfdPrice = lc.getFdPrice();
				
				_map.put("fdNum", BigDecimal.valueOf(fdNum-actualNum)+"");
				_map.put("fdPlanPrice", lc.getFdPlanPrice()+"");
				if((fdNum-actualNum) <= Double.parseDouble("0"))
				{
					_map.put("fdPrice", "0");
				}
				else
				{
					_map.put("fdPrice", BigDecimal.valueOf(((fdNum*fdPrice)-(actualNum*cfdPrice))/(fdNum-actualNum))+"");
				}
				
				dao.update("ZMCM2levelmaterialbase.updateInvalid1", _map);
			}
			else
			{
				Map tmp1 = ((ZMCM2levelbaseaccount)_list.get(0)).toMap();
				tmp1.put("fdKeyId", TablePk.getInstance().getNextValue("T_CM_2LEVELMATERIALBASE"));
				dao.insert("ZMCM2levelmaterialbase.insert", tmp1);
			}
		}
	}
}
